<template>
  <div class="laundry-orders">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>洗护订单管理</h1>
        <p class="description">管理所有洗护订单，跟踪订单状态，安排取件配送</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="refreshOrders">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon pending">
          <el-icon><Clock /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ orderStats.pending || 0 }}</h3>
          <p>待处理订单</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon processing">
          <el-icon><Loading /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ orderStats.processing || 0 }}</h3>
          <p>处理中订单</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon completed">
          <el-icon><Check /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ orderStats.completed || 0 }}</h3>
          <p>已完成订单</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon revenue">
          <el-icon><Money /></el-icon>
        </div>
        <div class="stat-content">
          <h3>¥{{ orderStats.todayRevenue || '0.00' }}</h3>
          <p>今日收入</p>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="客户手机">
          <el-input
            v-model="searchForm.customerPhone"
            placeholder="请输入客户手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="(label, value) in LAUNDRY_ORDER_STATUS"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型">
          <el-select
            v-model="searchForm.serviceType"
            placeholder="请选择服务类型"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="(label, value) in LAUNDRY_SERVICE_TYPE"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="orderList"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="140" />
        <el-table-column label="客户信息" width="140">
          <template #default="{ row }">
            <div class="customer-info">
              <div class="name">{{ row.customerName }}</div>
              <div class="phone">{{ row.customerPhone }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="服务项目" width="200">
          <template #default="{ row }">
            <div class="service-items">
              <div
                v-for="item in row.serviceItems"
                :key="item.id"
                class="service-item"
              >
                <span class="service-name">{{ item.serviceName }}</span>
                <span class="service-count">×{{ item.quantity }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="100">
          <template #default="{ row }">
            <span class="amount">¥{{ row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag
              :type="getStatusTagType(row.status)"
              effect="dark"
              size="small"
            >
              {{ LAUNDRY_ORDER_STATUS[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="取件时间" width="140">
          <template #default="{ row }">
            <div v-if="row.pickupDate">
              <div>{{ formatDate(row.pickupDate) }}</div>
              <div class="time-slot">{{ row.pickupTimeSlot }}</div>
            </div>
            <span v-else class="text-gray">未安排</span>
          </template>
        </el-table-column>
        <el-table-column label="配送时间" width="140">
          <template #default="{ row }">
            <div v-if="row.deliveryDate">
              <div>{{ formatDate(row.deliveryDate) }}</div>
              <div class="time-slot">{{ row.deliveryTimeSlot }}</div>
            </div>
            <span v-else class="text-gray">未安排</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="140">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                link
                size="small"
                @click="viewOrderDetail(row)"
              >
                查看详情
              </el-button>
              <el-button
                v-if="row.status === 'PENDING'"
                type="success"
                link
                size="small"
                @click="acceptOrder(row)"
              >
                接单
              </el-button>
              <el-button
                v-if="canSchedulePickup(row.status)"
                type="warning"
                link
                size="small"
                @click="schedulePickup(row)"
              >
                安排取件
              </el-button>
              <el-button
                v-if="canScheduleDelivery(row.status)"
                type="info"
                link
                size="small"
                @click="scheduleDelivery(row)"
              >
                安排配送
              </el-button>
              <el-dropdown
                v-if="row.status !== 'CANCELLED' && row.status !== 'DELIVERED'"
                @command="(command) => handleStatusChange(row, command)"
              >
                <el-button type="primary" link size="small">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-if="row.status === 'ACCEPTED'"
                      command="PICKED_UP"
                    >
                      标记已取件
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="row.status === 'PICKED_UP'"
                      command="IN_PROCESS"
                    >
                      开始处理
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="row.status === 'IN_PROCESS'"
                      command="QUALITY_CHECK"
                    >
                      质检完成
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="row.status === 'QUALITY_CHECK'"
                      command="READY"
                    >
                      制作完成
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="row.status === 'READY'"
                      command="DELIVERED"
                    >
                      标记已送达
                    </el-dropdown-item>
                    <el-dropdown-item command="CANCELLED" divided>
                      取消订单
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 订单详情弹窗 -->
    <OrderDetailDialog
      v-model:visible="detailDialogVisible"
      :order="selectedOrder"
      @refresh="refreshOrders"
    />

    <!-- 安排取件弹窗 -->
    <SchedulePickupDialog
      v-model:visible="pickupDialogVisible"
      :order="selectedOrder"
      @success="handleScheduleSuccess"
    />

    <!-- 安排配送弹窗 -->
    <ScheduleDeliveryDialog
      v-model:visible="deliveryDialogVisible"
      :order="selectedOrder"
      @success="handleScheduleSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  Clock,
  Loading,
  Check,
  Money,
  Search,
  ArrowDown
} from '@element-plus/icons-vue'
import {
  getLaundryOrders,
  acceptLaundryOrder,
  updateLaundryOrderStatus,
  schedulePickup as apiSchedulePickup,
  scheduleDelivery as apiScheduleDelivery,
  getOrderStats,
  LAUNDRY_ORDER_STATUS,
  LAUNDRY_SERVICE_TYPE
} from '@/api/laundry'
import OrderDetailDialog from './components/OrderDetailDialog.vue'
import SchedulePickupDialog from './components/SchedulePickupDialog.vue'
import ScheduleDeliveryDialog from './components/ScheduleDeliveryDialog.vue'

// 响应式数据
const loading = ref(false)
const orderList = ref([])
const selectedRows = ref([])
const selectedOrder = ref(null)
const detailDialogVisible = ref(false)
const pickupDialogVisible = ref(false)
const deliveryDialogVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  customerPhone: '',
  status: '',
  serviceType: '',
  dateRange: null
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 订单统计数据
const orderStats = ref({
  pending: 0,
  processing: 0,
  completed: 0,
  todayRevenue: '0.00'
})

// 计算属性
const canSchedulePickup = (status) => {
  return ['ACCEPTED'].includes(status)
}

const canScheduleDelivery = (status) => {
  return ['READY'].includes(status)
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusTypes = {
    PENDING: 'warning',
    ACCEPTED: 'primary',
    PICKED_UP: 'info',
    IN_PROCESS: 'warning',
    QUALITY_CHECK: 'primary',
    READY: 'success',
    DELIVERED: 'success',
    CANCELLED: 'danger',
    REFUNDED: 'info'
  }
  return statusTypes[status] || 'info'
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString()
}

const formatDateTime = (date) => {
  return new Date(date).toLocaleString()
}

// 方法
const loadOrders = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      orderNo: searchForm.orderNo,
      customerPhone: searchForm.customerPhone,
      status: searchForm.status,
      serviceType: searchForm.serviceType
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }

    const response = await getLaundryOrders(params)
    orderList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    ElMessage.error('获取订单列表失败')
    console.error('Load orders error:', error)
  } finally {
    loading.value = false
  }
}

const loadOrderStats = async () => {
  try {
    const response = await getOrderStats({
      date: new Date().toISOString().split('T')[0]
    })
    orderStats.value = response.data || {}
  } catch (error) {
    console.error('Load order stats error:', error)
  }
}

const refreshOrders = () => {
  loadOrders()
  loadOrderStats()
}

const handleSearch = () => {
  pagination.page = 1
  loadOrders()
}

const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    customerPhone: '',
    status: '',
    serviceType: '',
    dateRange: null
  })
  pagination.page = 1
  loadOrders()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (val) => {
  pagination.size = val
  pagination.page = 1
  loadOrders()
}

const handleCurrentChange = (val) => {
  pagination.page = val
  loadOrders()
}

const viewOrderDetail = (order) => {
  selectedOrder.value = order
  detailDialogVisible.value = true
}

const acceptOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要接受订单 ${order.orderNo} 吗？`,
      '确认接单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await acceptLaundryOrder(order.id, {
      acceptTime: new Date().toISOString()
    })

    ElMessage.success('接单成功')
    refreshOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('接单失败')
      console.error('Accept order error:', error)
    }
  }
}

const schedulePickup = (order) => {
  selectedOrder.value = order
  pickupDialogVisible.value = true
}

const scheduleDelivery = (order) => {
  selectedOrder.value = order
  deliveryDialogVisible.value = true
}

const handleScheduleSuccess = () => {
  refreshOrders()
}

const handleStatusChange = async (order, status) => {
  let confirmText = ''
  let successText = ''

  switch (status) {
    case 'PICKED_UP':
      confirmText = '确定标记订单为已取件吗？'
      successText = '标记成功'
      break
    case 'IN_PROCESS':
      confirmText = '确定开始处理订单吗？'
      successText = '状态更新成功'
      break
    case 'QUALITY_CHECK':
      confirmText = '确定完成质检吗？'
      successText = '质检完成'
      break
    case 'READY':
      confirmText = '确定订单制作完成吗？'
      successText = '制作完成'
      break
    case 'DELIVERED':
      confirmText = '确定订单已送达吗？'
      successText = '订单完成'
      break
    case 'CANCELLED':
      confirmText = '确定要取消订单吗？'
      successText = '订单已取消'
      break
    default:
      return
  }

  try {
    await ElMessageBox.confirm(confirmText, '状态更新', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: status === 'CANCELLED' ? 'warning' : 'info'
    })

    await updateLaundryOrderStatus(order.id, status)
    ElMessage.success(successText)
    refreshOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('状态更新失败')
      console.error('Update status error:', error)
    }
  }
}

// 生命周期
onMounted(() => {
  refreshOrders()
})
</script>

<style lang="scss" scoped>
.laundry-orders {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 10px;

    .header-left {
      h1 {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: #1f2937;
      }

      .description {
        margin: 0;
        color: #6b7280;
        font-size: 14px;
      }
    }
  }

  .stats-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 20px;
    margin-bottom: 30px;

    .stat-card {
      display: flex;
      align-items: center;
      padding: 20px;
      background: white;
      border-radius: 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      border: 1px solid #e5e7eb;

      .stat-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 48px;
        height: 48px;
        border-radius: 12px;
        margin-right: 16px;

        &.pending {
          background: linear-gradient(135deg, #fbbf24, #f59e0b);
          color: white;
        }

        &.processing {
          background: linear-gradient(135deg, #3b82f6, #2563eb);
          color: white;
        }

        &.completed {
          background: linear-gradient(135deg, #10b981, #059669);
          color: white;
        }

        &.revenue {
          background: linear-gradient(135deg, #8b5cf6, #7c3aed);
          color: white;
        }
      }

      .stat-content {
        h3 {
          margin: 0 0 4px 0;
          font-size: 24px;
          font-weight: 700;
          color: #1f2937;
        }

        p {
          margin: 0;
          font-size: 14px;
          color: #6b7280;
        }
      }
    }
  }

  .search-section {
    padding: 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }

  .table-section {
    background: white;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .customer-info {
      .name {
        font-weight: 600;
        color: #1f2937;
        margin-bottom: 2px;
      }

      .phone {
        font-size: 12px;
        color: #6b7280;
      }
    }

    .service-items {
      .service-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 4px;
        padding: 2px 8px;
        background: #f3f4f6;
        border-radius: 4px;
        font-size: 12px;

        &:last-child {
          margin-bottom: 0;
        }

        .service-name {
          color: #1f2937;
        }

        .service-count {
          color: #6b7280;
        }
      }
    }

    .amount {
      font-weight: 600;
      color: #dc2626;
    }

    .time-slot {
      font-size: 12px;
      color: #6b7280;
    }

    .text-gray {
      color: #9ca3af;
      font-size: 12px;
    }

    .action-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    padding: 20px;
  }
}
</style> 